package com.colin.jipay.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.colin.jipay.activity.MainActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Timer;

import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class PayHelperUtils {

	public static String ALI_USERID_RECEIVED_ACTION = "com.tools.payhelper.userid.received";
	public static String WECHATSTART_ACTION = "com.payhelper.wechat.start";
	public static String ALIPAYSTART_ACTION = "com.payhelper.alipay.start";
	public static String QQSTART_ACTION = "com.payhelper.qq.start";

	public static String MSGRECEIVED_ACTION = "com.colin.jipay.sendmsg";
	public static String TRADENORECEIVED_ACTION = "com.tools.payhelper.tradenoreceived";
	public static String LOGINIDRECEIVED_ACTION = "com.tools.payhelper.loginidreceived";
	public static String GETTRADEINFO_ACTION = "com.tools.payhelper.gettradeinfo";
	public static boolean isFirst=true;
	public static int triggerTime;
	public static Timer timer;
	public static Random rand;

	public static String dateToStamp(String d, String format) {
		String res = "";
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		try {
			return res = String.valueOf(simpleDateFormat.parse(d).getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return res;
	}



	public static void LogMsg(String str){
		Log.e("Xposed",str);
	}

	public static Observable<TextView> findTextViewByText(final ViewGroup viewGroup, final String text, final int retryCount) {
		return new Observable<TextView>() {
			@Override
			protected void subscribeActual(final Observer<? super TextView> observer) {
				final Runnable runnable = new Runnable() {
					ArrayList<View> outViews = new ArrayList<>();
					int count = retryCount;

					@Override
					public void run() {
						viewGroup.findViewsWithText(outViews, text, View.FIND_VIEWS_WITH_TEXT);
						if (outViews.isEmpty() || !outViews.get(0).isShown()) {
							if (--count < 0) {
								observer.onError(new Error("未找到`" + text + "`"));
							} else {
								MainActivity.handler.postDelayed(this, 500);
							}
						} else {
							observer.onNext((TextView) outViews.get(0));
							observer.onComplete();
						}
					}
				};

				observer.onSubscribe(new Disposable() {
					boolean isDisposed = false;

					@Override
					public void dispose() {
						MainActivity.handler.removeCallbacks(runnable);
						isDisposed = true;
					}

					@Override
					public boolean isDisposed() {
						return isDisposed;
					}
				});
				MainActivity.handler.post(runnable);
			}
		};
	}

	public static String getCookieStr(ClassLoader appClassLoader) {
		String cookieStr = "";
		// 获得cookieStr
		XposedHelpers.callStaticMethod(XposedHelpers.findClass(
				"com.alipay.mobile.common.transportext.biz.appevent.AmnetUserInfo", appClassLoader), "getSessionid");
		Context context = (Context) XposedHelpers.callStaticMethod(XposedHelpers.findClass(
				"com.alipay.mobile.common.transportext.biz.shared.ExtTransportEnv", appClassLoader), "getAppContext");
		if (context != null) {
			Object readSettingServerUrl = XposedHelpers.callStaticMethod(
					XposedHelpers.findClass("com.alipay.mobile.common.helper.ReadSettingServerUrl", appClassLoader),
					"getInstance");
			if (readSettingServerUrl != null) {
				// String gWFURL = (String)
				// XposedHelpers.callMethod(readSettingServerUrl, "getGWFURL",
				// context);
				String gWFURL = ".alipay.com";
				cookieStr = (String) XposedHelpers.callStaticMethod(XposedHelpers
								.findClass("com.alipay.mobile.common.transport.http.GwCookieCacheHelper", appClassLoader),
						"getCookie", gWFURL);
			} else {
				sendmsg(context, "异常readSettingServerUrl为空");
			}
		} else {
			sendmsg(context, "异常context为空");
		}
		return cookieStr;
	}

	public static String getOrderId() {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		String newDate=sdf.format(new Date());
		String result="";
		Random random=new Random();
		for(int i=0;i<3;i++){
			result+=random.nextInt(10);
		}
		return newDate+result;
	}

	public static void sendTradeInfo(Context context) {
		Intent broadCastIntent = new Intent();
		broadCastIntent.setAction(GETTRADEINFO_ACTION);
		context.sendBroadcast(broadCastIntent);
	}

	public static void  getTradeInfo(final Context context,final String cookie) {
		sendmsg(context, "有新的商家服务订单进来！！！");
		String url="https://mbillexprod.alipay.com/enterprise/walletTradeList.json?lastTradeNo=&lastDate=&pageSize=1&shopId=&_input_charset=utf-8&ctoken==&_ksTS=&_callback=&t="+System.currentTimeMillis();
		HttpUtils httpUtils = new HttpUtils(30000);
		httpUtils.configResponseTextCharset("GBK");
		RequestParams params = new RequestParams();
		params.addHeader("Cookie", cookie);
		params.addHeader("Referer", "https://render.alipay.com/p/z/merchant-mgnt/simple-order.html");
		params.addHeader("User-Agent", "Mozilla/5.0 (Linux; U; Android 7.1.1; zh-cn; Redmi Note 3 Build/LRX22G) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.100 U3/0.8.0 Mobile Safari/534.30 Nebula AlipayDefined(nt:WIFI,ws:360|640|3.0) AliApp(AP/10.1.22.835) AlipayClient/10.1.22.835 Language/zh-Hans useStatusBar/true");
		httpUtils.send(HttpRequest.HttpMethod.GET, url, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
//				sendmsg(context, "服务器异常" + arg1);
				sendmsg(context, "请求支付宝API失败，出现掉单，5秒后启动补单");
				sendTradeInfo(context);
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				String result = arg0.result.replace("/**/(", "").replace("})", "}");
				try {
					JSONObject jsonObject = new JSONObject(result);
					if(jsonObject.has("status")){
						String status=jsonObject.getString("status");
						if(!status.equals("deny")){
							JSONObject res = jsonObject.getJSONObject("result");
							JSONArray jsonArray = res.getJSONArray("list");
							if (jsonArray != null && jsonArray.length() > 0) {
								JSONObject object = jsonArray.getJSONObject(0);
								String tradeNo = object.getString("tradeNo");
								Intent broadCastIntent = new Intent();
								broadCastIntent.putExtra("tradeno", tradeNo);
								broadCastIntent.putExtra("cookie", cookie);
								broadCastIntent.setAction(TRADENORECEIVED_ACTION);
								context.sendBroadcast(broadCastIntent);
							}
						}else{
							sendmsg(context, "getTradeInfo=>>支付宝cookie失效，出现掉单，5秒后启动补单");
							sendTradeInfo(context);
						}
					}
				} catch (Exception e) {
					sendmsg(context,e.getMessage());
					XposedBridge.log("=====>"+arg0);
					sendmsg(context, "getTradeInfo出现异常=>>"+result);
					sendmsg(context, "出现掉单，5秒后启动补单");
					sendTradeInfo(context);
				}
			}
		});
	}

	/**
	 * 获取设备信息
	 */
	public static String getDevice(String type,Context context) {
		//import android.telephony.TelephonyManager;
		//<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
		//import android.os.Build;

		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		String Device="";
		if(type.equals("IMEI")){//串号
			Device = tm.getDeviceId() +"";
		}else if("DeviceSoftwareVersion".equals(type)){
			Device = tm.getDeviceSoftwareVersion() +"";
		}else if(type.equals("Line1Number")){//手机号码
			Device = tm.getLine1Number() +"";
		}else if(type.equals("NetworkCountryIso")){
			Device = tm.getNetworkCountryIso() +"";
		}else if(type.equals("NetworkOperator")){
			Device = tm.getNetworkOperator() +"";
		}else if(type.equals("NetworkOperatorName")){
			Device = tm.getNetworkOperatorName() +"";
		}else if(type.equals("NetworkType")){
			Device = tm.getNetworkType() +"";
		}else if(type.equals("PhoneType")){
			Device = tm.getPhoneType() +"";
		}else if(type.equals("SimCountryIso")){
			Device = tm.getSimCountryIso() +"";
		}else if(type.equals("SimOperator")){
			Device = tm.getSimOperator() +"";
		}else if(type.equals("SimOperatorName")){
			Device = tm.getSimOperatorName() +"";
		}else if(type.equals("SimSerialNumber")){
			Device = tm.getSimSerialNumber() +"";
		}else if(type.equals("SimState")){
			Device = tm.getSimState() +"";
		}else if(type.equals("IMSI")){
			Device = tm.getSubscriberId() +"";
		}else if(type.equals("VoiceMailNumber")){
			Device = tm.getVoiceMailNumber() +"";
		}else if(type.equals("phoneVersion")){//获取手机系统安卓版本 8.0.0
			Device = Build.VERSION.RELEASE +"";
		}else if(type.equals("phoneModel")){//获取手机型号 MIX3
			Device =  Build.MODEL +"";
		}
		return  Device;
	}

	/**
	 * 将图片转换成Base64编码的字符串
	 * 
	 * @param path
	 * @return base64编码的字符串
	 */
	public static String imageToBase64(String path) {
		if (TextUtils.isEmpty(path)) {
			return null;
		}
		InputStream is = null;
		byte[] data = null;
		String result = null;
		try {
			is = new FileInputStream(path);
			// 创建一个字符流大小的数组。
			data = new byte[is.available()];
			// 写入数组
			is.read(data);
			// 用默认的编码格式进行编码
			result = Base64.encodeToString(data, Base64.DEFAULT);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
		result = "\"data:image/gif;base64," + result + "\"";
		return result;
	}

	/*
	 * 将时间戳转换为时间
	 */
	public static String stampToDate(String s) {
		String res;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long lt = new Long(s);
		Date date = new Date(lt * 1000);
		res = simpleDateFormat.format(date);
		return res;
	}

	/**
	 * 方法描述：判断某一应用是否正在运行
	 * 
	 * @param context
	 *            上下文
	 * @param packageName
	 *            应用的包名
	 * @return true 表示正在运行，false表示没有运行
	 */
	public static boolean isAppRunning(Context context, String packageName) {
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> list = am.getRunningTasks(100);
		if (list.size() <= 0) {
			return false;
		}
		for (RunningTaskInfo info : list) {
			if (info.baseActivity.getPackageName().equals(packageName)) {
				return true;
			}
		}
		return false;
	}

	/*
	 * 启动一个app
	 */
	public static void startAPP(Context context, String appPackageName) {
		try {
			Intent intent = context.getPackageManager().getLaunchIntentForPackage(appPackageName);
			context.startActivity(intent);
		} catch (Exception e) {
			sendmsg(context, "startAPP异常" + e.getMessage());
		}
	}


	public static String getCurrentDate() {
		long l = System.currentTimeMillis();
		Date date = new Date(l);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String d = dateFormat.format(date);
		return d;
	}

	public static void sendmsg(Context context, String msg) {
		Intent broadCastIntent = new Intent();
		broadCastIntent.putExtra("msg", msg);
		broadCastIntent.setAction(MSGRECEIVED_ACTION);
		context.sendBroadcast(broadCastIntent);
	}

	/**
	 * 获取当前本地apk的版本
	 *
	 * @param mContext
	 * @return
	 */
	public static int getVersionCode(Context mContext) {
		int versionCode = 0;
		try {
			// 获取软件版本号，对应AndroidManifest.xml下android:versionCode
			versionCode = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
		} catch (PackageManager.NameNotFoundException e) {
			sendmsg(mContext, "getVersionCode异常" + e.getMessage());
		}
		return versionCode;
	}

	/**
	 * 获取版本号名称
	 *
	 * @param context
	 *            上下文
	 * @return
	 */
	public static String getVerName(Context context) {
		String verName = "";
		try {
			verName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
		} catch (PackageManager.NameNotFoundException e) {
			sendmsg(context, "getVerName异常" + e.getMessage());
		}
		return verName;
	}

	public static boolean isreg(Activity activity, String name) {
		Intent intent = new Intent();
		intent.setAction(name);
		PackageManager pm = activity.getPackageManager();
		List<ResolveInfo> resolveInfos = pm.queryBroadcastReceivers(intent, 0);
		if (resolveInfos != null && !resolveInfos.isEmpty()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 
	 * 判断某activity是否处于栈顶
	 * 
	 * @return true在栈顶 false不在栈顶
	 */
	public static int isActivityTop(Context context) {
		try {
			ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
			List<RunningTaskInfo> infos = manager.getRunningTasks(100);
			for (RunningTaskInfo runningTaskInfo : infos) {
				if (runningTaskInfo.topActivity.getClassName()
						.equals("cooperation.qwallet.plugin.QWalletPluginProxyActivity")) {
					return runningTaskInfo.numActivities;
				}
			}
			return 0;
		} catch (SecurityException e) {
			sendmsg(context, e.getMessage());
			return 0;
		}
	}


}
